﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Drawing;

namespace Spencen.Mobile.UI.Primitives
{
    public class EllipseElement : DrawingElement
    {
        public override bool HitTest( Point hitPoint, GraphicsContext context )
        {
            float distance = DrawingSupport.DistanceBetweenPoints( RelativeCenter , hitPoint );
            if ( distance > Size.Width / 2 && distance > Size.Height / 2 )
                return false;

            float hitAngle = DrawingSupport.AngleBetweenPoints( RelativeCenter, hitPoint );

            float distanceToCentreFromAngle =
                Size.Height / 2 + ( Size.Width / 2 - Size.Height / 2 ) * ( (float)Math.Abs( Math.Cos( DrawingSupport.DegToRad( hitAngle ) ) ) );

            return distance < distanceToCentreFromAngle;
        }

        private Point[] GeneratePoints()
        {
            var points = new Point[]
            {
                new Point( 0, 0 ),
                new Point( Size.Width, 0 ),
                new Point( Size.Width, Size.Height ),
                new Point( 0, Size.Height )
            };
            return points;
        }

        protected override void OnRender( GraphicsContext context )
        {
            var points = GeneratePoints();
            var transformedPoints = context.TransformedPoints( points );

            if ( Background != null )
            {
                context.Graphics.FillEllipse( Background,
                    (int)Math.Min( transformedPoints[ 0 ].X, transformedPoints[ 2 ].X ),
                    (int)Math.Min( transformedPoints[ 0 ].Y, transformedPoints[ 2 ].Y ),
                    (int)Math.Abs( transformedPoints[ 2 ].X - transformedPoints[ 0 ].X ),
                    (int)Math.Abs( transformedPoints[ 2 ].Y - transformedPoints[ 0 ].Y ) );
            }

            if ( Stroke != null )
            {
                context.Graphics.DrawEllipse( Stroke,
                    (int)Math.Min( transformedPoints[ 0 ].X, transformedPoints[ 2 ].X ),
                    (int)Math.Min( transformedPoints[ 0 ].Y, transformedPoints[ 2 ].Y ),
                    (int)Math.Abs( transformedPoints[ 2 ].X - transformedPoints[ 0 ].X ),
                    (int)Math.Abs( transformedPoints[ 2 ].Y - transformedPoints[ 0 ].Y ) );
            }
        }
    }
}
